<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of DAL
 *
 * @author Administrator
 */
class DAL_UserManagement {
    public static function CreateUser($user) {
        if(self::UserExist($user->email)!=null)
        {
            throw new Exception("该Email帐户已经存在");
        }
        
        $p = array(":email" => $user->email,
            ":password" => $user->password,
            ":username" => $user->username,
            ":is_verified" => $user->is_verified,
            ":is_active" => $user->is_active,
            ":is_admin" => $user->is_admin,
            ":createtime" => $user->createtime,
            ":ip" => $user->ip
        );
        if ($user->email != null && $user->email != "") {
            $p[":email"] = $user->email;
        }
        if ($user->password != null && $user->password != "") {
            $p[":password"] = $user->password;
        }
        if ($user->username != null && $user->username != "") {
            $p[":username"] = $user->username;
        }
        if ($user->is_verified != null && $user->is_verified != "") {
            $p[":is_verified"] = $user->is_verified;
        }
        if ($user->is_active != null && $user->is_active != "") {
            $p[":is_active"] = $user->is_active;
        }
        if ($user->is_admin != null && $user->is_admin != "") {
            $p[":is_admin"] = $user->is_admin;
        }
        if ($user->createtime != null && $user->createtime != "") {
            $p[":createtime"] = $user->createtime;
        }
        if ($user->ip != null && $user->ip != "") {
            $p[":ip"] = $user->ip;
        }

        $cols = "";
        $val = "";
        foreach ($p as $key => $value) {
            $cols.=trim($key, ":") . ",";
            $val.=$key . ",";
        }
        $cols = trim($cols, ",");
        $val = trim($val, ",");

        $sql = "insert into user ($cols) values($val)";
        $s = new SqliteHelper();
        $r=$s->ExecNoTans($sql, $p);
    }
    
    public static function UserExist($email)
    {
        $p = array(":email" => $email);
        $sql = "SELECT *  FROM user where email=:email";
        $Helper = new SqliteHelper();
        $result = $Helper->Query($sql, $p);
        if(count($result)>0)
        {
            return $result;
        }
        else
            return null;
    }
    
    public static function tryLogin($user)
    {
        $p = array(":email" => $user->email,":password"=>$user->password);
        $sql = "SELECT *  FROM user where email=:email and password=:password";
        $Helper = new SqliteHelper();
        $result = $Helper->Query($sql, $p);
        if(count($result)>0)
        {
            return $result[0];
        }
        else
            return null;
    }
}

?>
